﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Electure.DAL;

namespace Electure.Admin
{
    public partial class EditNewsItem : System.Web.UI.Page
    {
        int? Id
        {
            get
            {
                int? res = new int?();
                int id;
                if (int.TryParse(Request.QueryString["id"], out id))
                    res = id;
                return res;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            if (Id.HasValue)
            {
                using (var rep = RepositoryFactory.GetNewsRepository())
                {
                    var newsItem = rep.GetById(Id.Value);

                    tbName.Text = newsItem.Name;
                    tbDescription.Text = newsItem.Description;
                    imagePreview.Visible = true;
                    if (newsItem.Image != null)
                        imagePreview.ImageUrl = newsItem.Image.GetFullPath();
                    else
                        imagePreview.Visible = false;
                }
            }
        }

        protected void button_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Save")
            {
                int id;
                int? imageId = new int?();
                if (fuImage.HasFile)
                {
                    using (var rep = RepositoryFactory.GetAttachmentRepository())
                    {
                        int _imgId = rep.CreateImageAttachment(Request.PhysicalApplicationPath, fuImage.FileName, fuImage.PostedFile.ContentType, fuImage.FileContent);
                        if (_imgId != -1)
                            imageId = _imgId;
                    }
                }
                using (var rep = RepositoryFactory.GetNewsRepository())
                {
                    var instance = new News()
                    {
                        Name = tbName.Text,
                        Description = tbDescription.Text
                    };

                    if (imageId.HasValue)
                        instance.Image = new Attachment() { ID = imageId.Value };

                    if (!Id.HasValue)
                    {
                        id = rep.Create(instance);
                    }
                    else
                    {
                        instance.ID = Id.Value;
                        id = rep.Update(instance) ? Id.Value : -1;
                    }
                }

                if (id != -1)
                    Response.Redirect(string.Format("EditNews.aspx?id={0}", id));
            }
            else if (e.CommandName == "Cancel")
            {
                Response.Redirect("NewsList.aspx");
            }
        }
    }
}